package https

import (
	"../luahelper"
	"fmt"
	lua "github.com/yuin/gopher-lua"
	"strings"
)

func RegisterFunc_4lua(l *lua.LState) {
	table := l.SetFuncs(l.NewTable(), map[string]lua.LGFunction{
		"Post":      HttpPost_4lua,
		"Get":       HttpGet_4lua,
		"Do":        HttpDo_4lua,
		"SetCookie": SetCookie_4lua,
		"GetCookie": GetCookie_4lua,
	})

	l.SetGlobal("Http", table)
}

func HttpDo_4lua(l *lua.LState) int {
	// Http.Do({
	// 	Url = "",
	// 	Method = "GET",
	// 	Headers = {
	// 		["Content-Type"] = "application/json"
	// 	},
	// 	RequestBody = ""
	// })

	table := l.ToTable(1)
	if table == nil || table.Type() != lua.LTTable {
		return luahelper.PushErrorMessage(l, "input parameter error")
	}

	url := luahelper.GetTableStringFeild(table, "Url")
	if url == "" {
		return luahelper.PushErrorMessage(l, "not found url")
	}

	method := luahelper.GetTableStringFeild(table, "Method")
	if method == "" {
		method = "GET"
	}

	requestBody := luahelper.GetTableStringFeild(table, "RequestBody")

	headers := luahelper.GetTableTableFeild(table, "Headers")
	headerMap := make(map[string]string)

	if headers != nil {
		l.ForEach(headers, func(k lua.LValue, v lua.LValue) {
			if v.Type() == lua.LTString {
				headerMap[lua.LVAsString(k)] = lua.LVAsString(v)
			}
		})
	}

	respBody, err := HttpHandle(method, url, requestBody, headerMap)
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	return luahelper.PushStatusAndMessage(l, true, respBody)
}

// Get请求接口
func HttpGet_4lua(l *lua.LState) int {
	// Http.Get("http://www.baidu.com")
	url := l.ToString(1)

	if body, err := Get(url); err != nil {
		return luahelper.PushStatusAndMessage(l, false, err.Error())
	} else {
		return luahelper.PushStatusAndMessage(l, true, body)
	}
}

// Post请求接口
func HttpPost_4lua(l *lua.LState) int {
	// Http.Post("http://wwwlbaidu.com", "application/json", "{\"A\":11}")
	url := l.ToString(1)
	cType := l.ToString(2)
	body := l.ToString(3)

	if rbody, err := Post(url, cType, body); err != nil {
		return luahelper.PushStatusAndMessage(l, false, err.Error())
	} else {
		return luahelper.PushStatusAndMessage(l, true, rbody)
	}
}

func SetCookie_4lua(l *lua.LState) int {
	// Http.SetCookie("http://www.baidu.com"， "1=2;3=4")
	domain := l.ToString(1)
	cookie := l.ToString(2)

	SetCookie(domain, cookie)

	return 0
}

func GetCookie_4lua(l *lua.LState) int {
	// Http.GetCookie("http://www.baidu.com")

	domain := l.ToString(1)

	cookies, err := GetCookie(domain)
	if err != nil {
		return luahelper.PushErrorMessage(l, err.Error())
	}

	var cookie_list_str []string
	if cookies != nil && len(cookies) > 0 {
		for _, v := range cookies {
			cookie_list_str = append(cookie_list_str, fmt.Sprintf("%s=%s", v.Name, v.Value))
		}
	}

	if cookie_list_str != nil && len(cookie_list_str) > 0 {
		cookie_str := strings.Join(cookie_list_str, ";")
		return luahelper.PushStatusAndMessage(l, true, cookie_str)
	} else {
		return luahelper.PushStatus(l, false)
	}
}
